<?php

class ToolController extends Base {
	
	public $controllerPath = '';
	public $vuePath = '';

	public function testAction(){
		$config = Yaf_Registry::get('config');
		dd($config->tool);
	}

	public function tablesAction(){
		$tables = $this->db->query("show tables")->fetchAll();
		$list = [];
		foreach ($tables as $value) {
			$list[] = $value[0];
		}
		success($list);
	}

	public function columnsAction(){
		$tableName = $this->getRequest()->getQuery('table');
		$columns = $this->db->query("show full columns from ".$tableName)->fetchAll(PDO::FETCH_ASSOC);
		success($columns);
	}


	public function colsOptionAction(){
		$isGet = $this->getRequest()->isGet();
		$user = $this->getUser();
		if($isGet){
			$name = $this->getRequest()->getQuery('name');
			$find = $this->db->get('list_columns','*',['name'=>$name,'user_id'=>$user['id']]);
			$result = $find? json_decode($find['content'],true) : [];
			success($result);
		}else{
			$name = $this->getRequest()->getPost('name');
			$content = $this->getRequest()->getPost('content');
			$find = $this->db->get('list_columns','*',['name'=>$name,'user_id'=>$user['id']]);
			if($find){
				$this->db->update('list_columns',['content'=>$content],['name'=>$name]);
			}else{
				$this->db->insert('list_columns',['content'=>$content,'name'=>$name,'user_id'=>$user['id']]);
			}
			success();
		}
		

	}

	public function routesAction(){
		$config = Yaf_Registry::get('config');
		$path = $config->tool->controllerPath;
		$list = scan_dir($path);
		$result = [];
		foreach ($list as $value) {			
			$content = file_get_contents($value);
			preg_match('/([a-zA-Z0-9]*)Controller/', $content, $names);
			$name = lcfirst($names[1]);
			preg_match_all('/([a-zA-Z0-9]*)Action/', $content, $apis);
			$tmp = [];
			$tmp[] = [
				'id'=>$name.'.*',
				'parentId'=>$name,
				'title'=>'all',
			];
			$keys = [];
			foreach ($apis[1] as $key => $value) {
				if(!$value){
					continue;
				}
				$keys[] = $value;
				$tmp[] = [
						'id'=>$name.'.'.$value,
						'parentId'=>$name,
						'title'=>$value,
					];
			}
			if(strpos($content, 'CURD')){
				if(!in_array('index',$keys)){
					$tmp[] = [
						'id'=>$name.'.'.'index',
						'parentId'=>$name,
						'title'=>'index',
					];
				}
				if(!in_array('store',$keys)){
					$tmp[] = [
						'id'=>$name.'.'.'store',
						'parentId'=>$name,
						'title'=>'store',
					];
				}
				if(!in_array('dict',$keys)){
					$tmp[] = [
						'id'=>$name.'.'.'dict',
						'parentId'=>$name,
						'title'=>'dict',
					];
				}
				if(!in_array('remove',$keys)){
					$tmp[] = [
						'id'=>$name.'.'.'remove',
						'parentId'=>$name,
						'title'=>'remove',
					];
				}
			}
			$result[] = [
				'id'=>$name,
				'title'=>$name,
				'children'=>$tmp
			];
		}
		success($result);
	}

	//代码生成
	public function generateAction(){
		$config = Yaf_Registry::get('config');
		if(!$config->tool){
			error('代码生成工具参数未配置{tool.enable,tool.controllerPath,tool.heyAdminPath}');
		}
		if(!$config->tool->enable){
			error('代码生成工具未开启{tool.enable}');
		}
		if(!$config->tool->controllerPath){
			error('代码生成工具PHP接口生成路径未配置{tool.controllerPath}');
		}
		if(!$config->tool->heyAdminPath){
			error('代码生成工具前段根目录未配置{tool.heyAdminPath}');
		}
		$this->controllerPath = $config->tool->controllerPath;
		$this->vuePath = $config->tool->heyAdminPath."\src\components\demo-components";
		$requestFile = $config->tool->heyAdminPath."\src\js\common\\request.js";
		if(!file_exists($requestFile)){
			error($requestFile.'文件不存在');
		}
		$routeFile = $config->tool->heyAdminPath."\src\js\config\demo-components.js";
		if(!file_exists($routeFile)){
			error($routeFile.'文件不存在');
		}
		$menuFile = $config->tool->heyAdminPath."\src\js\config\menu-config.js";
		if(!file_exists($menuFile)){
			error($menuFile.'文件不存在');
		}
		$requestFileContent = file_get_contents($requestFile);
		$apiPushEndPosition = strpos($requestFileContent,'//apiPushEnd');
		if(!$apiPushEndPosition){
			error($requestFile.'文件必须包含//apiPushEnd,用于替换新增代码');
		}	
		$routeFileContent = file_get_contents($routeFile);	
		$componentPushEndPos = strpos($routeFileContent,'//componentPushEnd');
		if(!$componentPushEndPos){
			error($routeFile.'文件必须包含//componentPushEnd,用于替换新增代码');
		}	
		$menuFileContent = file_get_contents($menuFile);
		$menuPushEndPos = strpos($menuFileContent,'//menuPushEnd');	
		if(!$menuPushEndPos){
			error($menuFile.'文件必须包含//menuPushEnd,用于替换新增代码');
		}
		$table = $this->getRequest()->getPost('table');
		$php = $this->getRequest()->getPost('php');
		$list = $this->getRequest()->getPost('list');
		$form = $this->getRequest()->getPost('form');
		$detail = $this->getRequest()->getPost('detail');
		

		if(!$table){
			error("请传递参数{table}");
		}

		if(!$php){
			error("请传递参数{php}");
		}

		if(!$list){
			error("请传递参数{list}");
		}

		if(!$form){
			error("请传递参数{form}");
		}

		if(strpos($menuFileContent,$table."List")){
			error($menuFile.'文件菜单Key['.$table."List]已存在");
		}

		// SQL插入菜单与权限all
		$parent_id = $this->getRequest()->getPost('parent_id',0);
		$name = $this->getRequest()->getPost('name','未命名');
		$count = $this->db->count('admin_menu',['key'=>$table.'List']);
		if(!$count){
			$admin_menu_item = [
				'key'=>$table.'List',
				'title'=>$name,
				'show'=>1,
				'parent_id'=>$parent_id,
				'order'=>10
			];
			$this->db->insert('admin_menu',$admin_menu_item);
			$this->db->insert('admin_permissions',[
				'http_path'=>lcfirst($table).'.*',
				'name'=>'列表',
				'slug'=>'base',
				'parent_id'=>$table.'List',
			]);
		}

		//写入菜单
		$menuFileContent = str_replace('//menuPushEnd', ",{title: '".$table."', key: '".$table."List'}\n//menuPushEnd", $menuFileContent);
		file_put_contents($menuFile,$menuFileContent);

		//定义api
		$action = lcfirst($table);
		if(strpos($requestFileContent,"tasks.push('".$action."');")){
			error($requestFile.'文件必须已包含'."tasks.push('".$action."');");
		}		
		$requestFileContent = str_replace('//apiPushEnd', "tasks.push('".$action."');\n//apiPushEnd", $requestFileContent);
		file_put_contents($requestFile,$requestFileContent);


		//定义Vue组件路由
		$routeFileContent = str_replace('//componentPushEnd', "Componts.push({
  path: '/".$action."',
  name: '".$table."List',
  component: (resolve) => require(['components/demo-components/".$action."/list'], resolve),
  meta: { title: 'list' }
});\n//componentPushEnd", $routeFileContent);
		file_put_contents($routeFile,$routeFileContent);
		

		$existFile = $this->controllerPath.'\\'.ucfirst(strtolower($table)).'.php';
		$myfile = fopen($existFile, "w") or die("Unable to open file!");
		fwrite($myfile, $php);
		fclose($myfile);
		$folder = $this->vuePath.'\\'.$action;
		if(!file_exists($folder)){
			mkdir($folder);
		}
		$listFile = $folder.'\\list.vue';
		$myfile = fopen($listFile, "w") or die("Unable to open file!");
		fwrite($myfile, $list);
		fclose($myfile);

		$listFile = $folder.'\\form.vue';
		$myfile = fopen($listFile, "w") or die("Unable to open file!");
		fwrite($myfile, $form);
		fclose($myfile);

		$listFile = $folder.'\\detail.vue';
		$myfile = fopen($listFile, "w") or die("Unable to open file!");
		fwrite($myfile, $detail);
		fclose($myfile);

		success($this->controllerPath);
	}
}
